//
//  M_FuliVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/27.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class M_FuliVC: BaseViewControllerWithHeader {
    var dataListAry = [[String:Any?]]()
    var pageIndex = 1
    var pageSize = 20
    var totalSize = 2000
    
    //列表控件
    var tableView = QuickTableView<[String:Any?],M_FuliCell>()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        refreshAll()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func OpenWelfare(welfareRecordID: String) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "welfareRecordID":welfareRecordID]
        API.request(url: .M_OpenWelfare, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                let popup = PopupBox(infoText: "领取成功")
                popup.show(vc: UIViewController.topMostController() ?? self)
                self.refreshAll()
            }
            else {
                let popup = PopupBox(infoText:result.errMsg ?? "当前红包已打开")
                popup.show(vc: UIViewController.topMostController() ?? UIViewController())
            }
        }
    }
    
    func getDataList(pageIndex: Int, pageSize:Int) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "pageIndex":pageIndex,
                                    "pageSize":pageSize,
                                    "sort":"107001",
                                    "dir":"106001"]
        API.request(url: .M_GetUserWelfareFlowHistory, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    for item in dl.getDictList("items") ?? [] {
                        self.dataListAry.append(item)
                    }
                    self.queryData()
                    self.pageIndex = dl.getInt("pageIndex") ?? 0
                    self.totalSize = dl.getInt("totalSize") ?? 0
                }
            }
        }
    }
}

// MARK:- UI
extension M_FuliVC {
    func setupUI() {
        headView.backgroundColor = .white
        headTitle.text = "福利领取"
        safeView.backgroundColor = .xF2F2F2
        
        //添加列表
        safeView.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(headView.snp.bottom)
            make.bottom.equalToSuperview()
        }
        tableView.backgroundColor = .xF7F7F7
                        
        //当点击表格行时
        tableView.onDataSelectedSubject().bindWeak(self) { (data, s) in
        }
        
        //刷新相关事件绑定
        tableView.onSetCellSubject().bindWeak(self) { (cell, s) in
            cell.callAddBlock(block: { (data) in
                self.OpenWelfare(welfareRecordID: data.getString("welfareRecordID") ?? "")
            })
        }
        
        //当表底上拉刷新更多时
        tableView.footerLoadMoreSubject.bindWeak(self) { (s) in
            s.getNextPage()
        }
        
        //当表头下拉刷新时
        tableView.headerRequerySubject.bindWeak(self) { (s) in
            s.refreshAll()
            self.tableView.reloadForHeaderRequery(list: self.dataListAry, isLastPage: false)
        }
        
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

    }
}

// MARK:- 事件
extension M_FuliVC {
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    func queryData() {
        tableView.list = dataListAry
        tableView.reloadData()
    }
    
    func getNextPage() {
        
        if pageIndex*pageSize < totalSize {
            getDataList(pageIndex: pageIndex+1, pageSize: pageSize)
            tableView.reloadForFooterLoadMore(list: dataListAry, isLastPage: false)
        } else {
            tableView.reloadForFooterLoadMore(list: dataListAry, isLastPage: true)
        }
    }
    
    func refreshAll() {
        dataListAry.removeAll()
        getDataList(pageIndex: 1, pageSize: pageSize)
    }
}
